package io.gitee.kotle.android.mvvm

import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import io.gitee.kotle.android.BaseLibraryConfig
import io.gitee.kotle.android.delegate.unsafeLazy
import io.gitee.kotle.android.mvvm.mvvminterface.IBaseMvvm
import io.gitee.kotle.android.mvvm.mvvminterface.ScreenOrientationHelper
import io.gitee.kotle.android.utils.ScreenAdaptationObj
import io.gitee.kotle.android.utils.ignoreError
import io.gitee.kotle.android.utils.isScreenPortrait
import io.gitee.kotle.android.utils.updateLocal

/**
 * 所有activity的基类
 */
abstract class MvvmActivity : AppCompatActivity(), IBaseMvvm {
    private val screenOrientationHelper by unsafeLazy { ScreenOrientationHelper(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //region 将view与activity关联
        val container = findViewById<ViewGroup>(android.R.id.content)
        onHandleCreateMvvmViewType(layoutInflater, container, savedInstanceState)?.let {
            setContentView(it, it.layoutParams)
        }
        //endregion
        onViewCreatedFinish(this, savedInstanceState, resources)
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        //处理安卓8.0报错
        //Only fullscreen activities can request orientation
        ignoreError { super.setRequestedOrientation(requestedOrientation) }
    }

    override fun getResources(): Resources {
        val resources = super.getResources()
        onScreenAdaptation(resources)
        return resources
    }

    /**
     * 屏幕适配
     */
    open fun onScreenAdaptation(resources: Resources) {
        ScreenAdaptationObj.setCustomDensity(
            resources,
            BaseLibraryConfig.enableScreenAdaptation && isNeedScreenAdaptation()
        )
    }

    /**
     * 如果支持多语言的话，更新语言
     */
    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(if (BaseLibraryConfig.autoUpdateLocal) newBase?.updateLocal() else newBase)
    }

    /**
     * 是否需要屏幕适配
     */
    protected open fun isNeedScreenAdaptation() = true

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        checkScreenPortrait(resources)
    }


    final override fun checkScreenPortrait(resources: Resources) {
        screenOrientationHelper.checkScreenPortrait(resources)
    }
}